package com.hzncc.scaffold.controller.Front.Course;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.druid.support.http.util.IPAddress;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.util.StringUtil;
import com.hzncc.scaffold.config.MinioConfig;
import com.hzncc.scaffold.core.ResultT;
import com.hzncc.scaffold.entity.Bo.LibExerciseRecordBo;
import com.hzncc.scaffold.entity.Bo.ScheduledAnswerBo;
import com.hzncc.scaffold.entity.Bo.UserAnswerBo;
import com.hzncc.scaffold.entity.Other.*;
import com.hzncc.scaffold.entity.Vo.*;
import com.hzncc.scaffold.mapper.*;
import com.hzncc.scaffold.service.*;
import com.hzncc.scaffold.utils.AESEncrypt;
import com.hzncc.scaffold.utils.NumberUtils;
import com.hzncc.scaffold.utils.TimeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.xml.crypto.Data;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @Author: DrunkBear
 * @Date: 2022-06-06 15:32
 * @Description: null
 */
@Api(tags = "前台接口-课程")
@RequestMapping("/course")
@RestController
public class CourseController {

    @Autowired
    UserService userService;

    @Autowired
    QuestionlibService questionlibService;

    @Autowired
    CourseService courseService;

    @Autowired
    CourseMapper courseMapper;

    @Autowired
    ChapterMapper chapterMapper;

    @Autowired
    TaskprogressService taskprogressService;

    @Autowired
    UsercollectcourseService usercollectcourseService;

    @Autowired
    UserjoinedcourseService userjoinedcourseService;

    @Autowired
    TaskService taskService;

    @Autowired
    LibexerciserecordMapper libexerciserecordMapper;

    @Autowired
    LibexerciserecordService libexerciserecordService;

    @Autowired
    QuestionService questionService;

    @Autowired
    TaskMapper taskMapper;

    @Autowired
    QuestionMapper questionMapper;

    @Autowired
    PaperService paperService;

    @Autowired
    LibexercisesummaryService libexercisesummaryService;

    @Autowired
    PaperrecordService paperrecordService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    UsertagService usertagService;

    @Autowired
    ChapterService chapterService;


    @Autowired
    ExerciserecordMapper exerciserecordMapper;

    @Autowired
    MinioConfig minioConfig;

    @Value("${project.imgFileSuffix}")
    public String imgFileSuffix;


    @GetMapping("/list")
    @ApiOperation("课程管理列表")
    public ResultT list(Integer pageNum, Integer pageSize, Integer majorId, Integer isFree, String keyword, Integer isExercise, Integer page) {
        Integer pageData = NumberUtils.pageNum(page, pageNum);
        ResultT resultT = questionlibService.listQuestionLibPlus(pageData, pageSize, majorId, isFree, keyword, isExercise);

        return resultT;
    }

    @GetMapping("/detail")
    @ApiOperation("获取课程详情")
    public ResultT detail(Integer courseId) {

        QueryWrapper<Course> qw = new QueryWrapper<>();
        qw.eq("course.id", courseId);

        CourseChaptersDatilVo myCourseVo = courseMapper.courseDetailPlus(qw);
        LambdaQueryWrapper<Chapter> lqwe = new LambdaQueryWrapper<>();
        lqwe.eq(Chapter::getCourseId, myCourseVo.getId()).orderByAsc(Chapter::getRank);
        List<ChaptersVo> chaptersVos = new ArrayList<>();
        List<Chapter> chapterList = chapterService.list(lqwe);
        for (Chapter chapter : chapterList) {
            ChaptersVo chaptersVo = new ChaptersVo();
            org.springframework.beans.BeanUtils.copyProperties(chapter, chaptersVo);
            LambdaQueryWrapper<Task> lqww = new LambdaQueryWrapper<>();
            lqww.eq(Task::getChapterId, chapter.getId()).orderByAsc(Task::getRank);
            List<Task> taskList = taskService.list(lqww);
            chaptersVo.setTasks(taskList);
            chaptersVos.add(chaptersVo);
        }
        myCourseVo.setChapters(chaptersVos);
        LambdaQueryWrapper<Usercollectcourse> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Usercollectcourse::getCourseId, courseId);
        List<Integer> collector = usercollectcourseService.list(lqw).stream().map(usercollectcourse -> usercollectcourse.getUserId()).collect(Collectors.toList());
        myCourseVo.setCollector(collector);

        boolean joined = false;
        List<Integer> taskArr = new ArrayList<>();
        boolean collected = false;
        List<Integer> courseLearner = courseMapper.courseUsers(courseId);
        int aa = StpUtil.getLoginIdAsInt();
        System.out.println("当前登录id："+aa);
        if (CollUtil.isNotEmpty(courseLearner) && courseLearner.contains(StpUtil.getLoginIdAsInt())) {
            Integer courseTask = 0;
            for (ChaptersVo chapter : myCourseVo.getChapters()) {
                courseTask += chapter.getTasks().size();
            }
            LambdaQueryWrapper<Taskprogress> lqww = new LambdaQueryWrapper<>();
            lqww.eq(Taskprogress::getUserId, StpUtil.getLoginIdAsInt());
            lqww.eq(Taskprogress::getCourseId, myCourseVo.getId());
            lqww.eq(Taskprogress::getIsFinished, true);
            List<Taskprogress> taskprogressList = taskprogressService.list(lqww);
            Integer finishedTask = taskprogressList.size();
            String finishedPercentage = NumberUtil.mul(NumberUtil.div(finishedTask, courseTask, 2), 100) + "%";
            if ((finishedTask + 1) == courseTask) {
                myCourseVo.setExamAccess(true);
            } else {
                myCourseVo.setExamAccess(false);
            }
            myCourseVo.setFinishedTask(finishedTask);
            myCourseVo.setFinishedPercentage(finishedPercentage);

            if (CollUtil.isNotEmpty(taskprogressList)) {
                taskArr = taskprogressList.stream().map(c -> c.getTaskId()).collect(Collectors.toList());
            }
            joined = true;
        }

        if (CollUtil.isNotEmpty(myCourseVo.getCollector())) {
            for (Integer integer : myCourseVo.getCollector()) {
                if (integer == StpUtil.getLoginIdAsInt()) {
                    collected = true;
                }
            }
        }

        if (CollUtil.isNotEmpty(myCourseVo.getChapters())) {
            for (ChaptersVo c : myCourseVo.getChapters()) {
                for (Task tas : c.getTasks()) {
                    if (taskArr.contains(tas.getId())) {
                        tas.setIsFinished(true);
                    } else {
                        tas.setIsFinished(false);
                    }
                }
            }
        }
        myCourseVo.setJoined(joined);
        myCourseVo.setCollected(collected);
        if (StringUtils.isNotEmpty(myCourseVo.getCover())) {
            myCourseVo.setCover(imgFileSuffix + myCourseVo.getCover());
        }
        return ResultT.success(myCourseVo);
    }

    @PostMapping("/collect")
    @ApiOperation("课程收藏")
    public ResultT collect(@RequestBody CollectVo collectVo) {
        if (!StpUtil.isLogin()) {
            return ResultT.fail("用户未登录");
        }

        Boolean collected = collectVo.getCollected();
        String courseId = collectVo.getCourseId();

        if (collected) {
            Usercollectcourse usercollectcourse = new Usercollectcourse();
            usercollectcourse.setUserId(StpUtil.getLoginIdAsInt());
            usercollectcourse.setCourseId(Integer.parseInt(courseId));

            boolean save = usercollectcourseService.save(usercollectcourse);
            if (save) {
                return ResultT.success("操作成功");
            } else {
                return ResultT.fail("操作失败");
            }
        } else {
            LambdaQueryWrapper<Usercollectcourse> lqw = new LambdaQueryWrapper<>();
            lqw.eq(Usercollectcourse::getUserId, StpUtil.getLoginIdAsInt());
            lqw.eq(Usercollectcourse::getCourseId, courseId);

            boolean remove = usercollectcourseService.remove(lqw);

            if (remove) {
                return ResultT.success("操作成功");
            } else {
                return ResultT.fail("操作失败");
            }
        }
    }

//    @PostMapping("/join")
//    @ApiOperation("加入课程")
//    public ResultT join(@RequestBody CourseIdVo courseIdVo) {
//        if (!StpUtil.isLogin()) {
//            return ResultT.fail("用户未登录");
//        }
//        Integer courseId = courseIdVo.getCourseId();
//
//        if (courseService.getById(courseId) == null) {
//            return ResultT.fail("数据错误");
//        }
//
//        Course course = courseService.getById(courseId);
//        User user = userService.getById(StpUtil.getLoginIdAsInt());
//
//        if (StrUtil.isNotEmpty(course.getAuthentation())) {
//            List<String> authentationList = StrUtil.split(course.getAuthentation(), ",");
//
//            LambdaQueryWrapper<Usertag> lqw = new LambdaQueryWrapper<>();
//            lqw.eq(Usertag::getUserId, StpUtil.getLoginIdAsInt());
//            if (CollUtil.isEmpty(usertagService.list(lqw))) {
//                return ResultT.fail("数据错误");
//            }
//            List<Integer> userTagList = usertagService.list(lqw).stream().map(usertag -> usertag.getTagId()).collect(Collectors.toList());
//            List<String> userTagStrList = userTagList.stream().map(String::valueOf).collect(Collectors.toList());
//
//            authentationList.retainAll(userTagStrList);
//
//            if (CollUtil.isEmpty(authentationList)) {
//                return ResultT.fail("您没有权限，请先开通权限");
//            } else {
//                if (user.getVipTime() != null) {
//                    if (DateUtil.compare(DateUtil.date(), DateUtil.parse(user.getVipTime(), "yyyy-MM-dd")) > 0) {
//                        return ResultT.fail("您没有权限，请先开通权限");
//                    }
//                }
//            }
//        } else {
//            return ResultT.fail("加入失败");
//        }
//
//        LambdaQueryWrapper<Userjoinedcourse> lqw = new LambdaQueryWrapper<>();
//        lqw.eq(Userjoinedcourse::getCourseId, courseId);
//        lqw.eq(Userjoinedcourse::getUserId, StpUtil.getLoginIdAsInt());
//
//        if (CollUtil.isNotEmpty(userjoinedcourseService.list(lqw))) {
//            return ResultT.fail("您已加入该课程");
//        }
//
//        Userjoinedcourse userjoinedcourse = new Userjoinedcourse();
//        userjoinedcourse.setCourseId(courseId);
//        userjoinedcourse.setUserId(StpUtil.getLoginIdAsInt());
//        userjoinedcourse.setCreateTime(DateUtil.date());
//
//        boolean save = userjoinedcourseService.save(userjoinedcourse);
//        if (save) {
//
//            Taskprogress taskprogress = new Taskprogress();
//            taskprogress.setUserId(StpUtil.getLoginIdAsInt());
//            taskprogress.setCreateTime(DateUtil.now());
//
//            LambdaQueryWrapper<Chapter> lqww = new LambdaQueryWrapper<>();
//            lqww.eq(Chapter::getCourseId, courseIdVo.getCourseId());
//            Chapter chapter = chapterService.getOne(lqww);
//
//            LambdaQueryWrapper<Task> lqwww = new LambdaQueryWrapper<>();
//            lqwww.eq(Task::getChapterId, chapter.getId());
//            Task task = taskService.getOne(lqwww);
//
//            taskprogress.setTaskId(task.getId());
//            taskprogress.setCreateTime(DateUtil.now());
//
//            taskprogressService.save(taskprogress);
//
//            return ResultT.success("操作成功");
//        } else {
//            return ResultT.fail("操作失败");
//        }
//    }

    @PostMapping("/join")
    @ApiOperation("加入课程")
    public ResultT join(@RequestBody CourseIdVo courseIdVo) {
        if (!StpUtil.isLogin()) {
            return ResultT.fail("用户未登录");
        }
        Integer courseId = courseIdVo.getCourseId();

        if (courseService.getById(courseId) == null) {
            return ResultT.fail("数据错误");
        }

        Course course = courseService.getById(courseId);
        User user = userService.getById(StpUtil.getLoginIdAsInt());

        if (StrUtil.isNotEmpty(course.getAuthentation())) {
            List<String> authentationList = StrUtil.split(course.getAuthentation(), ",");

            LambdaQueryWrapper<Usertag> lqw = new LambdaQueryWrapper<>();
            lqw.eq(Usertag::getUserId, StpUtil.getLoginIdAsInt());
            if (CollUtil.isEmpty(usertagService.list(lqw))) {
                return ResultT.fail("数据错误");
            }
            List<Integer> userTagList = usertagService.list(lqw).stream().map(usertag -> usertag.getTagId()).collect(Collectors.toList());
            List<String> userTagStrList = userTagList.stream().map(String::valueOf).collect(Collectors.toList());

            authentationList.retainAll(userTagStrList);

            if (CollUtil.isEmpty(authentationList)) {
                return ResultT.fail("您没有权限，请先开通权限",426);
            } else {
                if (user.getVipTime() != null) {
                    if (DateUtil.compare(DateUtil.date(), DateUtil.parse(user.getVipTime(), "yyyy-MM-dd")) > 0) {
                        return ResultT.fail("您没有权限，请先开通权限",426);
                    }
                }
            }
        } else {
            return ResultT.fail("加入失败");
        }

        LambdaQueryWrapper<Userjoinedcourse> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Userjoinedcourse::getCourseId, courseId);
        lqw.eq(Userjoinedcourse::getUserId, StpUtil.getLoginIdAsInt());

        if (CollUtil.isNotEmpty(userjoinedcourseService.list(lqw))) {
            return ResultT.fail("您已加入该课程");
        }

        Userjoinedcourse userjoinedcourse = new Userjoinedcourse();
        userjoinedcourse.setCourseId(courseId);
        userjoinedcourse.setUserId(StpUtil.getLoginIdAsInt());
        userjoinedcourse.setCreateTime(DateUtil.date());

        boolean save = userjoinedcourseService.save(userjoinedcourse);
        if (save) {

            Taskprogress taskprogress = new Taskprogress();
            taskprogress.setUserId(StpUtil.getLoginIdAsInt());
            taskprogress.setCreateTime(DateUtil.now());

            LambdaQueryWrapper<Chapter> lqww = new LambdaQueryWrapper<>();
            lqww.eq(Chapter::getCourseId, courseIdVo.getCourseId());

            List<Chapter> chapterList = chapterService.list(lqww);

            for (Chapter chapter : chapterList) {
                LambdaQueryWrapper<Task> lqwww = new LambdaQueryWrapper<>();
                lqwww.eq(Task::getChapterId, chapter.getId());
                List<Task> taskList = taskService.list(lqwww);

                for (Task task : taskList) {
                    taskprogress.setTaskId(task.getId());
                    taskprogress.setCreateTime(DateUtil.now());
                    taskprogress.setCourseId(courseIdVo.getCourseId());
                }
            }
            taskprogressService.save(taskprogress);

            return ResultT.success("操作成功");
        } else {
            return ResultT.fail("操作失败");
        }
    }

    @GetMapping("/task/detail")
    @ApiOperation("教学课堂目录详情")
    public ResultT taskDetail(Integer taskId, Boolean joined) {

//        CourseTaskVo courseTaskVo = BeanUtil.toBean(taskService.getById(taskId), CourseTaskVo.class);


//        LambdaQueryWrapper<Taskprogress> lqw = new LambdaQueryWrapper<>();
////        lqw.eq(Taskprogress::getUserId, StpUtil.getLoginIdAsInt());
//        lqw.eq(Taskprogress::getTaskId, taskId);
//        Taskprogress taskprogress = taskprogressService.getOne(lqw);
//        if (BeanUtil.isNotEmpty(taskprogress)) {
//            if (taskprogress.getIsFinished() == 0) {
//                courseTaskVo.setIsFinished(false);
//            } else {
//                courseTaskVo.setIsFinished(true);
//            }
//            courseTaskVo.setJoined(true);
//            courseTaskVo.setStudyTime(taskprogress.getStudyTime());
//        }


        Task task = taskService.getById(taskId);
        CourseTaskVo courseTaskVo = BeanUtil.toBean(task, CourseTaskVo.class);
        if (BeanUtil.isEmpty(task)) {
            return ResultT.fail();
        }
        Chapter chapter = chapterMapper.selectById(task.getChapterId());
//            if (BeanUtil.isNotEmpty(chapter)) {
//                Course course = courseMapper.selectById(chapter.getCourseId());
//            }
        Paper paper = paperService.getById(task.getPaperId());
        LambdaQueryWrapper<Taskprogress> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Taskprogress::getTaskId, taskId);
        List<Taskprogress> list = taskprogressService.list(lqw);
        Boolean isFinished = false;
        String studyTime = null;
        for (Taskprogress taskprogress : list) {
            if (taskprogress.getUserId() == StpUtil.getLoginIdAsInt()) {
                isFinished = taskprogress.getIsFinished();
                studyTime = taskprogress.getStudyTime();
            }
        }
        courseTaskVo.setIsFinished(isFinished);
        courseTaskVo.setStudyTime(studyTime);

        if (task.getType() == 3 && (task.getExamType() == 0 || task.getExamType() == 1)) {
            courseTaskVo.setHasOperationQuestion(true);
            if (StpUtil.isLogin()) {
                LambdaQueryWrapper<Paperrecord> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(Paperrecord::getUserId, StpUtil.getLoginIdAsInt()).eq(Paperrecord::getCourseId, chapter.getCourseId())
                        .last("limit 1").orderByDesc(Paperrecord::getCreateTime);
                Paperrecord one = paperrecordService.getOne(wrapper);
                if (BeanUtil.isNotEmpty(one)) {
                    if (null != one.getOperationScore()) {
                        courseTaskVo.setOperationQuestionFinished(true);
                        courseTaskVo.setOperationQuestionAccess(true);
                    } else {
                        courseTaskVo.setOperationQuestionFinished(false);
                        if (paper.getPassScore() <= one.getTheoryScore()) {
                            courseTaskVo.setOperationQuestionAccess(true);
                        } else {
                            courseTaskVo.setOperationQuestionAccess(false);
                        }
                    }

                } else {
                    if (task.getExamType() == 1) {
                        courseTaskVo.setOperationQuestionAccess(true);
                    } else {
                        courseTaskVo.setOperationQuestionAccess(false);
                    }
                }
            }

        } else {
            courseTaskVo.setHasOperationQuestion(false);
        }

        courseTaskVo.setJoined(joined);
        if (StpUtil.isLogin()) {
            if (courseTaskVo.getJoined()) {
                ResultT.success(courseTaskVo);
            } else {
                if (task.getIsFree() != 1) {
                    ResultT.fail();
                } else {
                    ResultT.success(courseTaskVo);
                }
            }
        } else {
            if (task.getIsFree() != 1) {
                ResultT.fail();
            } else {
                ResultT.success(courseTaskVo);
            }
        }
        return ResultT.success(courseTaskVo);
    }

    @GetMapping("/task/libExerciseRecordList")
    @ApiOperation("获取题库训练答题记录列表")
    public ResultT taskLibExerciseRecordList(Integer taskId) {

        QueryWrapper<LibExerciseRecordBo> qw = new QueryWrapper<>();
        qw.eq("libexerciserecord.userId", StpUtil.getLoginIdAsInt());
        qw.eq("libexerciserecord.taskId", taskId);
        qw.orderByDesc("libexerciserecord.id");
        List<LibExerciseRecordBo> libExerciseRecordBos = libexerciserecordMapper.taskLibExerciseRecordList(qw);
        List<LibExerciseRecordVo> libExerciseRecordVos = BeanUtil.copyToList(libExerciseRecordBos, LibExerciseRecordVo.class);
        Map<String, Object> map = new HashMap<>();
        map.put("count", libExerciseRecordVos.size());
        map.put("rows", libExerciseRecordVos);
        return ResultT.success(map);
    }

    @GetMapping("task/libExerciseSummary")
    @ApiOperation("显示题库训练题数")
    public ResultT libExerciseSummary(Integer taskId) {

        LibExerciseSummaryVo libExerciseSummaryVo = new LibExerciseSummaryVo();

        LambdaQueryWrapper<Libexercisesummary> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Libexercisesummary::getTaskId, taskId);
        lqw.eq(Libexercisesummary::getUserId, StpUtil.getLoginIdAsInt());

        Libexercisesummary summary = libexercisesummaryService.getOne(lqw);
        List<Integer> questionArr = new ArrayList<>();
        List<Integer> answered = new ArrayList<>();
        List<Integer> wrongArr = new ArrayList<>();

        Task task = taskService.getById(taskId);
        if (task.getQuestionLibId() != null) {
            LambdaQueryWrapper<Question> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Question::getLibId, task.getQuestionLibId());
            lambdaQueryWrapper.notIn(Question::getType, 3);
            List<Question> questionList = questionService.list(lambdaQueryWrapper);
            task.setQuestionList(questionList);
        }
        if (CollUtil.isNotEmpty(task.getQuestionList())) {
            questionArr = task.getQuestionList().stream().map(c -> c.getId()).collect(Collectors.toList());
        }


        if (BeanUtil.isNotEmpty(summary) && StringUtils.isNotEmpty(summary.getRecord())) {
            List<AnswerVo> answerVo = JSONUtil.toList(summary.getRecord(), AnswerVo.class);
            answered = answerVo.stream().map(a -> a.getId()).collect(Collectors.toList());
            wrongArr = answerVo.stream().filter(c -> c.getCorrect() == 0).map(a -> a.getId()).collect(Collectors.toList());
            for (int i = 0; i < questionArr.size(); i++) {
                for (int j = 0; j < answered.size(); j++) {
                    if (questionArr.get(i).equals(answered.get(j))) {
                        questionArr.remove(i);
                        i -= 1;
                        break;
                    }
                }
            }
        }
        libExerciseSummaryVo.setAnsweredArr(answered);
        libExerciseSummaryVo.setUnansweredArr(questionArr);
        libExerciseSummaryVo.setWrongArr(wrongArr);
        return ResultT.success(libExerciseSummaryVo);
    }

    @GetMapping("/continue")
    @ApiOperation("教学课堂继续学习")
    public ResultT continueCourse(@RequestParam Integer courseId) throws InvocationTargetException, IllegalAccessException {
        if (!StpUtil.isLogin()) {
            return ResultT.fail("当前用户未登录");
        }
        QueryWrapper<Taskprogress> qw = new QueryWrapper<>();
        qw.eq("taskprogress.courseId", courseId);
        qw.eq("taskprogress.userId", StpUtil.getLoginIdAsInt());
        qw.orderByAsc("taskprogress.isFinished");
        qw.orderByDesc("taskprogress.createTime");
//        qw.in("task.type",0,1);
        ContinueVo continueVo = new ContinueVo();
        List<ContinueVo> continueVos = taskMapper.continueCourseList(qw);
        if (CollUtil.isNotEmpty(continueVos)) {
            List<ContinueVo> collect = continueVos.stream().filter(c -> !c.getIsFinished()).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(collect)) {
                return ResultT.success(collect.get(0));
            } else {
                LambdaQueryWrapper<Chapter> characterQueryWrapper = new LambdaQueryWrapper<>();
                characterQueryWrapper.eq(Chapter::getCourseId, courseId).orderByAsc(Chapter::getRank);
                List<Chapter> chapters = chapterMapper.selectList(characterQueryWrapper);
                List<Integer> collect1 = chapters.stream().map(Chapter::getId).collect(Collectors.toList());
                LambdaQueryWrapper<Task> taskprogressQueryWrapper = new LambdaQueryWrapper<>();
                taskprogressQueryWrapper.in(Task::getChapterId, collect1).orderByAsc(Task::getRank);
                taskprogressQueryWrapper.in(Task::getType, 0, 1);
                List<Task> tasks = taskMapper.selectList(taskprogressQueryWrapper);
                if (CollUtil.isNotEmpty(tasks)) {
                    List<Integer> collect2 = tasks.stream().map(c -> c.getId()).collect(Collectors.toList());
                    List<Integer> collect3 = continueVos.stream().map(c -> c.getId()).collect(Collectors.toList());
                    List<Integer> collectDelete = collect2.stream().filter(it -> !collect3.contains(it)).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(collectDelete)) {
                        List<Task> collect4 = tasks.stream().filter(c -> c.getId() == collectDelete.get(0)).collect(Collectors.toList());
                        Task task = new Task();
                        if (CollUtil.isNotEmpty(collect4)) {
                            task = collect4.get(0);
                        } else {
                            task = tasks.get(0);
                        }

                        continueVo.setId(task.getId());
                        if (null != collect4.get(0).getResourceUrl()) {
                            continueVo.setResourceUrl(task.getResourceUrl());
                        }
                        if (null != task.getTitle()) {
                            continueVo.setTitle(task.getTitle());
                        }
                        if (null != task.getType()) {
                            continueVo.setType(task.getType());
                        }
                        if (null != task.getRank()) {
                            continueVo.setRank(task.getRank());
                        }
                        if (null != task.getPaperId()) {
                            continueVo.setPaperId(task.getPaperId());
                        }
                        continueVo.setIsFinished(false);
                    }
                    ContinueVo continueVo1 = continueVos.get(continueVos.size() - 1);
                    return ResultT.success(continueVo1);
                } else {
                    BeanUtils.copyProperties(continueVo, continueVos.get(0));
                    continueVo.setIsFinished(true);
                    return ResultT.success(continueVo);
                }
            }
        } else {
            LambdaQueryWrapper<Chapter> characterQueryWrapper = new LambdaQueryWrapper<>();
            characterQueryWrapper.eq(Chapter::getCourseId, courseId).orderByAsc(Chapter::getRank);
            List<Chapter> chapters = chapterMapper.selectList(characterQueryWrapper);
            List<Integer> collect1 = chapters.stream().map(Chapter::getId).collect(Collectors.toList());
            LambdaQueryWrapper<Task> taskprogressQueryWrapper = new LambdaQueryWrapper<>();
            taskprogressQueryWrapper.in(Task::getChapterId, collect1).orderByAsc(Task::getRank);
//            taskprogressQueryWrapper.in(Task::getType, 0, 1);
            List<Task> tasks = taskMapper.selectList(taskprogressQueryWrapper);
            if (CollUtil.isNotEmpty(tasks)) {
                Task task = tasks.get(0);
                continueVo.setId(task.getId());
                if (null != task.getResourceUrl()) {
                    continueVo.setResourceUrl(task.getResourceUrl());
                }
                if (null != task.getTitle()) {
                    continueVo.setTitle(task.getTitle());
                }
                if (null != task.getType()) {
                    continueVo.setType(task.getType());
                }
                if (null != task.getRank()) {
                    continueVo.setRank(task.getRank());
                }
                if (null != task.getPaperId()) {
                    continueVo.setPaperId(task.getPaperId());
                }
                continueVo.setIsFinished(false);
            }

        }

        return ResultT.success(continueVo);
    }

    @PostMapping("/task/libExerciseQuestions")
    @ApiOperation("答题筛选")
    public ResultT libExerciseQuestions(@RequestBody libExerciseQuestionsVo libExerciseQuestionsVo) {

        Integer taskId = libExerciseQuestionsVo.getTaskId();
        String questionArr = libExerciseQuestionsVo.getQuestionArr();
        String taskTitle = "";

        if (taskService.getById(taskId) != null) {
            Task task = taskService.getById(taskId);
            taskTitle = task.getTitle();
        }

        questionArr = questionArr.substring(1, questionArr.length() - 1);
        List<String> questionArrList = StrUtil.split(questionArr, ",");

        questionArrList = this.createRandoms(questionArrList, 50);

        QueryWrapper<ListQuestionVo> statisticsQw1 = new QueryWrapper<>();
        statisticsQw1.in("question.id", questionArrList);
        statisticsQw1.eq("question.type", 0);
        Integer singleNum = questionMapper.statisticsQuestion(statisticsQw1);

        QueryWrapper<ListQuestionVo> statisticsQw2 = new QueryWrapper<>();
        statisticsQw2.in("question.id", questionArrList);
        statisticsQw2.eq("question.type", 1);
        Integer multiNum = questionMapper.statisticsQuestion(statisticsQw2);

        QueryWrapper<ListQuestionVo> statisticsQw3 = new QueryWrapper<>();
        statisticsQw3.in("question.id", questionArrList);
        statisticsQw3.eq("question.type", 2);
        Integer judgeNum = questionMapper.statisticsQuestion(statisticsQw3);

        QueryWrapper<ListQuestionVo> qw = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(questionArr)) {
            qw.in("question.id", questionArrList);
        }
        List<ListQuestionVo> listQuestionVos = questionMapper.listQuestion(qw);

        String listQuestionVosJsonStr = JSON.toJSONString(listQuestionVos);

        //AES加密
        AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, "w2SIy2Hx%2i!tTCd-ikwHEv_kQmB58xI".getBytes(), "R7#54X&gLB!6Q&s=".getBytes());
        String theoryQuestion = aes.encryptBase64(listQuestionVosJsonStr);

        ExerciseQuestionVo exerciseQuestionVo = new ExerciseQuestionVo();
        exerciseQuestionVo.setTheoryQuestion(theoryQuestion);
        exerciseQuestionVo.setSingleNum(singleNum);
        exerciseQuestionVo.setMultiNum(multiNum);
        exerciseQuestionVo.setJudgeNum(judgeNum);
        exerciseQuestionVo.setTaskTitle(taskTitle);

        return ResultT.success(exerciseQuestionVo);
    }


    private List<String> createRandoms(List<String> list, int n) {
        Map<Integer, String> map = new HashMap();
        List<String> newList = new ArrayList();
        if (list.size() <= n) {
            return list;
        } else {
            while (map.size() < n) {
                int random = (int) (Math.random() * list.size());
                if (!map.containsKey(random)) {
                    map.put(random, "");
                    newList.add(list.get(random));
                }
            }
            return newList;
        }
    }

    @PostMapping("/task/commitLibExercise")
    @ApiOperation("提交题库训练试卷")
    public ResultT commitLibExercise(@RequestBody CommitLibExerciseVo commitLibExerciseVo) {
        String voAnswer = commitLibExerciseVo.getAnswer();

        //AES解密
        AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, "w2SIy2Hx%2i!tTCd-ikwHEv_kQmB58xI".getBytes(), "R7#54X&gLB!6Q&s=".getBytes());
        String decryptStr = aes.decryptStr(voAnswer, CharsetUtil.CHARSET_UTF_8);

        List<AnswerVo> answer = JSONUtil.toList(decryptStr, AnswerVo.class);
        Integer questionCount = answer.size();
        Integer wrongCount = 0;
        Integer rightCount = 0;

        for (AnswerVo answerBeanVo : answer) {
            if (answerBeanVo.getCorrect() == 0) {
                wrongCount++;
            } else {
                rightCount++;
            }
        }
        String accuracy = new BigDecimal(rightCount).multiply(new BigDecimal(100)).divide(new BigDecimal(questionCount), 2, BigDecimal.ROUND_UP).toString() + "%";

        AccuracyVo accuracyVo = new AccuracyVo();
        accuracyVo.setAccuracy(accuracy);

        //存入练习记录
        Libexerciserecord libexerciserecord = new Libexerciserecord();
        libexerciserecord.setUserId(StpUtil.getLoginIdAsInt());
        libexerciserecord.setTaskId(commitLibExerciseVo.getTaskId());
        int offsetMinutes = TimeUtils.getOffsetMinutes(DateUtil.parse(commitLibExerciseVo.getStartTime(), "yyyy-MM-dd HH:mm:ss"), DateUtil.parse(commitLibExerciseVo.getEndTime(), "yyyy-MM-dd HH:mm:ss"));
        libexerciserecord.setExerciseTime(offsetMinutes == 0 ? "1" : offsetMinutes + "");
        libexerciserecord.setQuestionCount(questionCount);
        libexerciserecord.setRightCount(rightCount);
        libexerciserecord.setWrongCount(wrongCount);
        libexerciserecord.setAccuracy(accuracy);
        libexerciserecord.setAnswer(decryptStr);
        libexerciserecord.setStartTime(commitLibExerciseVo.getStartTime());
        libexerciserecord.setEndTime(commitLibExerciseVo.getEndTime());
        libexerciserecord.setCreateTime(DateUtil.format(new Date(), "YYYY-MM-DD HH:mm:ss"));
        libexerciserecordService.save(libexerciserecord);

        //存入练习统计
        LambdaQueryWrapper<Libexercisesummary> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Libexercisesummary::getUserId, StpUtil.getLoginIdAsInt());
        lambdaQueryWrapper.eq(Libexercisesummary::getTaskId, commitLibExerciseVo.getTaskId());
        lambdaQueryWrapper.last("limit 1");
        Libexercisesummary lib = libexercisesummaryService.getOne(lambdaQueryWrapper);
        if (BeanUtil.isEmpty(lib)) {
            Libexercisesummary libexercisesummary = new Libexercisesummary();
            libexercisesummary.setUserId(StpUtil.getLoginIdAsInt());
            libexercisesummary.setTaskId(commitLibExerciseVo.getTaskId());
            libexercisesummary.setRecord(decryptStr);
            libexercisesummary.setCreateTime(DateUtil.format(new Date(), "YYYY-MM-DD HH:mm:ss"));
            libexercisesummaryService.save(libexercisesummary);
        } else {
            if (StringUtils.isNotEmpty(lib.getRecord())) {
                List<AnswerVo> answerVo = JSONUtil.toList(lib.getRecord(), AnswerVo.class);
                for (AnswerVo vo : answerVo) {
                    for (int i = 0; i < answer.size(); i++) {
                        if (vo.getId().equals(answer.get(i).getId())) {
                            vo.getCorrect().equals(answer.get(i).getCorrect());
                            answer.remove(i);
                            i--;
                        }
                    }
                }
                answerVo.addAll(answer);
                lib.setRecord(JSONUtil.toJsonStr(answerVo));
                libexercisesummaryService.updateById(lib);
            }
        }
        LambdaQueryWrapper<Taskprogress> taskprogressLambdaQueryWrapper = new LambdaQueryWrapper<>();
        taskprogressLambdaQueryWrapper.eq(Taskprogress::getUserId, StpUtil.getLoginIdAsInt());
        taskprogressLambdaQueryWrapper.eq(Taskprogress::getTaskId, commitLibExerciseVo.getTaskId());
        taskprogressLambdaQueryWrapper.last("limit 1");
        Taskprogress taskprogress = taskprogressService.getOne(taskprogressLambdaQueryWrapper);
        if (BeanUtil.isEmpty(taskprogress)) {
            taskprogress = new Taskprogress();
            taskprogress.setUserId(StpUtil.getLoginIdAsInt());
            taskprogress.setTaskId(commitLibExerciseVo.getTaskId());
            taskprogress.setCourseId(commitLibExerciseVo.getCourseId());
            taskprogress.setCreateTime(DateUtil.format(new Date(), "YYYY-MM-DD HH:mm:ss"));
            taskprogressService.save(taskprogress);
        }
        if (!taskprogress.getIsFinished()) {
            List<AnswerVo> recordJson = new ArrayList<>();
            if(BeanUtil.isNotEmpty(lib) && StringUtils.isNotEmpty(lib.getRecord())){
                recordJson = JSONUtil.toList(lib.getRecord(), AnswerVo.class);
            }
            Task task = taskMapper.selectById(commitLibExerciseVo.getTaskId());
            LambdaQueryWrapper<Question> questionLambdaQueryWrapper = new LambdaQueryWrapper<>();
            questionLambdaQueryWrapper.eq(Question::getLibId, task.getQuestionLibId());
            questionLambdaQueryWrapper.notIn(Question::getType, 3);
            Integer count = questionService.count(questionLambdaQueryWrapper);
            if (count.equals(recordJson.size())) {
                taskprogress.setIsFinished(true);
                taskprogressService.saveOrUpdate(taskprogress);
            }
        }
        return ResultT.success(accuracyVo);
    }

    @GetMapping("/task/libExerciseRecordDetail")
    @ApiOperation("获取题库训练记录详情")
    public ResultT libExerciseRecordDetail(Integer recordId) {

        if (libexerciserecordService.getById(recordId) == null) {
            return ResultT.fail("数据错误");
        }

        Libexerciserecord libexerciserecord = libexerciserecordService.getById(recordId);

        String answer = libexerciserecord.getAnswer();
        List<Integer> questionIdList = JSONUtil.toList(answer, AnswerVo.class).stream().map(AnswerVo::getId).collect(Collectors.toList());

        QueryWrapper<Question> qw = new QueryWrapper<>();
        qw.in("question.id", questionIdList);
        List<ListQuestionVo> listQuestionVos = questionMapper.listQuestion(qw);
        String theoryQuestion = JSONUtil.toJsonStr(listQuestionVos);
        Integer singleNum = 0;
        Integer multiNum = 0;
        Integer judgeNum = 0;
        for (ListQuestionVo listQuestionVo : listQuestionVos) {
            if ((listQuestionVo.getType().equals(0))) {
                singleNum++;
            } else {
                if ((listQuestionVo.getType().equals(1))) {
                    multiNum++;
                } else {
                    judgeNum++;
                }
            }
        }

        //AES加密
        AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, "w2SIy2Hx%2i!tTCd-ikwHEv_kQmB58xI".getBytes(), "R7#54X&gLB!6Q&s=".getBytes());
        theoryQuestion = aes.encryptBase64(theoryQuestion);
//
//        QueryWrapper<ListQuestionVo> statisticsQw1 = new QueryWrapper<>();
//        statisticsQw1.in("question.id", questionIdList);
//        statisticsQw1.eq("question.type", 0);
//         singleNum = questionMapper.statisticsQuestion(statisticsQw1);
//
//        QueryWrapper<ListQuestionVo> statisticsQw2 = new QueryWrapper<>();
//        statisticsQw2.in("question.id", questionIdList);
//        statisticsQw2.eq("question.type", 1);
//         multiNum = questionMapper.statisticsQuestion(statisticsQw2);
//
//        QueryWrapper<ListQuestionVo> statisticsQw3 = new QueryWrapper<>();
//        statisticsQw3.in("question.id", questionIdList);
//        statisticsQw3.eq("question.type", 2);
//         judgeNum = questionMapper.statisticsQuestion(statisticsQw3);
//
//
        LibExerciseRecordDetailVo libExerciseRecordDetailVo = new LibExerciseRecordDetailVo();
        if (taskService.getById(libexerciserecord.getTaskId()) != null) {
            libExerciseRecordDetailVo.setTaskTitle(taskService.getById(libexerciserecord.getTaskId()).getTitle());
        }
        libExerciseRecordDetailVo.setTheoryQuestion(theoryQuestion);
        libExerciseRecordDetailVo.setUserAnswer(libexerciserecord.getAnswer());
        libExerciseRecordDetailVo.setSingleNum(singleNum);
        libExerciseRecordDetailVo.setMultiNum(multiNum);
        libExerciseRecordDetailVo.setJudgeNum(judgeNum);

        return ResultT.success(libExerciseRecordDetailVo);
    }

//    @GetMapping("/task/libExerciseRecordExist")
//    @ApiOperation("判断是否有答题记录")
//    public ResultT libExerciseRecordExist(Integer taskId) {
//
//        LambdaQueryWrapper<Libexerciserecord> lqw = new LambdaQueryWrapper<>();
//        lqw.eq(taskId != null, Libexerciserecord::getTaskId, taskId);
//        List<Libexerciserecord> libexerciserecordList = libexerciserecordService.list(lqw);
//
//        if (CollUtil.isNotEmpty(libexerciserecordList)) {
//            Integer isExist = 1;
//            return ResultT.success(isExist);
//        } else {
//            Integer isExist = 0;
//            return ResultT.success(isExist);
//        }
//    }

    @GetMapping("/task/paperDetail")
    @ApiOperation("教学课堂目录查看测试，理论考试详情")
    public ResultT paperDetail(Integer paperId, Integer taskId, Integer courseId, Integer type, Boolean isFinished) throws InvocationTargetException, IllegalAccessException {

        Task task = taskService.getById(taskId);
        Paper paper = paperService.getById(paperId);
        paper.setIv("R7#54X&gLB!6Q&s=");
        paper.setKey("w2SIy2Hx%2i!tTCd-ikwHEv_kQmB58xI");
        if (BeanUtil.isNotEmpty(task)) {
            paper.setTaskTitle(task.getTitle());
        }
        String paperTitle = paper.getTheoryQuestion();
        Paperrecord record = new Paperrecord();
        if (isFinished) {
            if (type == 3) {
                LambdaQueryWrapper<Paperrecord> lqw = new LambdaQueryWrapper<>();
                lqw.eq(Paperrecord::getUserId, StpUtil.getLoginIdAsInt());
                lqw.eq(Paperrecord::getCourseId, courseId);
                record = paperrecordService.getOne(lqw);
                String userAnswer = record.getUserAnswer();
                List<UserAnswerBo> sorttedTheoryQuestion = new ArrayList<>();
                if (StringUtils.isNotEmpty(userAnswer)) {

                    List<UserAnswerBo> userAnswerBos = JSONObject.parseArray(userAnswer, UserAnswerBo.class);
                    List<UserAnswerBo> userAnswerBos1 = JSONObject.parseArray(paperTitle, UserAnswerBo.class);
                    for (UserAnswerBo userAnswerBo : userAnswerBos) {
                        for (UserAnswerBo answerBo : userAnswerBos1) {
                            if (answerBo.getId().equals(userAnswerBo.getId())) {
                                sorttedTheoryQuestion.add(answerBo);
                                break;
                            }
                        }
                    }
                };
                paper.setTheoryQuestion(AESEncrypt.encode(paper.getKey(),CollUtil.isEmpty(sorttedTheoryQuestion)?paper.getTheoryQuestion():JSONUtil.toJsonStr(sorttedTheoryQuestion), paper.getIv().getBytes()));
            } else {
                LambdaQueryWrapper<Exerciserecord> lqw = new LambdaQueryWrapper<>();
                lqw.eq(courseId != null, Exerciserecord::getTaskId, courseId)
                        .orderByDesc(Exerciserecord::getCreateTime).last(" limit 1");
                lqw.eq(Exerciserecord::getUserId, StpUtil.getLoginIdAsInt());
                Exerciserecord exerciserecord = exerciserecordMapper.selectOne(lqw);
                org.springframework.beans.BeanUtils.copyProperties(exerciserecord,record);
            }
            if (BeanUtil.isNotEmpty(record)) {
                org.springframework.beans.BeanUtils.copyProperties(record,paper);
                return ResultT.success(paper);
            } else {
                return ResultT.success(paper);
            }
        } else {
            LambdaQueryWrapper<Paperrecord> pap = new LambdaQueryWrapper<>();
            pap.eq(Paperrecord::getUserId, StpUtil.getLoginIdAsInt());
            pap.eq(Paperrecord::getTaskId, taskId);
            pap.eq(Paperrecord::getPaperId, paperId);
            pap.eq(Paperrecord::getResetted, true);
            pap.orderByDesc(Paperrecord::getCreateTime);
            pap.last("limit 1");
            Paperrecord paperrecord = paperrecordService.getOne(pap);

            String uniqueStr = courseId + "-" + taskId + "-" + paperId + "-" + StpUtil.getLoginIdAsInt();
            String scheduledAnswer = (String) redisTemplate.opsForValue().get(uniqueStr);
            if (StringUtils.isNotEmpty(scheduledAnswer) && BeanUtil.isEmpty(paperrecord)) {
                ScheduledAnswerBo scheduledAnswerBo = JSON.parseObject(scheduledAnswer, ScheduledAnswerBo.class);
                if (BeanUtil.isNotEmpty(scheduledAnswerBo)) {
                    paper.setTimeUse(scheduledAnswerBo.getTimeUse());
//                    paperDetailVo.setUserAnswer(AESEncrypt.encode(paperDetailVo.getKey(),scheduledAnswerBo.getUserAnswer(), paperDetailVo.getIv().getBytes()));
                    paper.setUserAnswer(scheduledAnswerBo.getUserAnswer());
                }
            } else {
                //开始考试
                Date date = new Date();
                Date afterDate = new Date(date.getTime() + (paper.getExamTime() + 1) * 60000);
                paper.setTimeUse("0");
                //创建定时器对象
                Timer timer = new Timer();
                List<UserAnswerBo> userAnswerBos = JSONObject.parseArray(paper.getTheoryQuestion(), UserAnswerBo.class);
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        String scheduledAnswer = (String) redisTemplate.opsForValue().get(uniqueStr);
                        String[] arr = uniqueStr.split("-");
                        Integer paperId2 = Integer.valueOf(arr[2]);
                        if (StringUtils.isNotEmpty(scheduledAnswer)) {
                            List<ScheduledAnswerBo> scheduledAnswerBos = JSONObject.parseArray(scheduledAnswer, ScheduledAnswerBo.class);
                            Integer theoryScore = 0;
                            if (CollUtil.isNotEmpty(scheduledAnswerBos)) {
                                String userAnswer = scheduledAnswerBos.get(0).getUserAnswer();
                                if (StringUtils.isNotEmpty(userAnswer)) {
                                    List<UserAnswerBo> userAnswerBoList = JSONObject.parseArray(userAnswer, UserAnswerBo.class);
                                    for (UserAnswerBo userAnswerBo : userAnswerBoList) {
                                        for (UserAnswerBo answerBo : userAnswerBos) {
                                            if (answerBo.getId() == userAnswerBo.getId()) {
                                                if (answerBo.getAnswer() == userAnswerBo.getAnswer()) {
                                                    if (answerBo.getType() == 0) {
                                                        theoryScore = theoryScore + paper.getPerSingle();
                                                    } else if (answerBo.getType() == 1) {
                                                        theoryScore = theoryScore + paper.getPerMulti();
                                                    } else if (answerBo.getType() == 2) {
                                                        theoryScore = theoryScore + paper.getPerJudge();
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                String timeUse = scheduledAnswerBos.get(0).getTimeUse();
                                Integer passed = task.getExamType() == 0 && theoryScore >= paper.getPassScore() ? 1 : 0;
                                String dateTime = DateUtil.formatDateTime(new Date());
                                if (type == 3) {
                                    LambdaQueryWrapper<Paperrecord> lqw = new LambdaQueryWrapper<>();
                                    lqw.eq(courseId != null, Paperrecord::getCourseId, courseId).orderByDesc(Paperrecord::getCreateTime).last(" limit 1");
                                    lqw.eq(Paperrecord::getUserId, StpUtil.getLoginIdAsInt());
                                    Paperrecord paperrecord = paperrecordService.getOne(lqw);
                                    if (BeanUtil.isEmpty(paperrecord)) {
                                        Paperrecord paperrecord1 = new Paperrecord();
                                        paperrecord1.setTheoryScore(theoryScore);
                                        paperrecord1.setPaperId(paperId2);
                                        paperrecord1.setPassed(passed);
                                        paperrecord1.setUserId(StpUtil.getLoginIdAsInt());
                                        paperrecord1.setCourseId(courseId);
                                        paperrecord1.setTimeUse(timeUse);
                                        paperrecord1.setUserAnswer(userAnswer);
                                        paperrecord1.setCreateTime(dateTime);
                                        paperrecord1.setTaskId(taskId);
                                    }
                                } else {
                                    LambdaQueryWrapper<Exerciserecord> lqw = new LambdaQueryWrapper<>();
                                    lqw.eq(courseId != null, Exerciserecord::getTaskId, courseId).orderByDesc(Exerciserecord::getCreateTime).last(" limit 1");
                                    lqw.eq(Exerciserecord::getUserId, StpUtil.getLoginIdAsInt());
                                    Exerciserecord exerciserecord = exerciserecordMapper.selectOne(lqw);
                                    Exerciserecord exerciserecord1 = new Exerciserecord();
                                    exerciserecord1.setTheoryScore(theoryScore);
                                    exerciserecord1.setPaperId(paperId2);
                                    exerciserecord1.setPassed(passed);
                                    exerciserecord1.setUserId(StpUtil.getLoginIdAsInt());
//                                        paperrecord1.setCourseId(courseId);
                                    exerciserecord1.setTimeUse(timeUse);
                                    exerciserecord1.setUserAnswer(userAnswer);
                                    exerciserecord1.setCreateTime(dateTime);
                                    exerciserecord1.setTaskId(taskId);
                                    if (BeanUtil.isEmpty(exerciserecord)) {
                                        exerciserecordMapper.insert(exerciserecord1);
                                    }
                                }
                                redisTemplate.delete(uniqueStr);
                            }
                        }
                    }
                }, afterDate);
                if (BeanUtil.isNotEmpty(paperrecord)) {
                    paper.setUserAnswer(null);
                    paper.setTimeUse("0");
                }
            }
        }
        List<UserAnswerBo> singleList = new ArrayList<>();
        List<UserAnswerBo> multiList = new ArrayList<>();
        List<UserAnswerBo> judgeList = new ArrayList<>();


        if (StringUtils.isNotEmpty(paperTitle)) {
            List<UserAnswerBo> userAnswerBos = JSONObject.parseArray(paper.getTheoryQuestion(), UserAnswerBo.class);
            if (CollUtil.isNotEmpty(userAnswerBos)) {
                String theoryQuestion1 = paper.getTheoryQuestion();
                List<UserAnswerBo> userAnswerBoList = JSONObject.parseArray(theoryQuestion1, UserAnswerBo.class);
                for (UserAnswerBo userAnswerBo : userAnswerBoList) {
                    if (userAnswerBo.getType() == 0) {
                        singleList.add(userAnswerBo);
                    }
                    if (userAnswerBo.getType() == 1) {
                        multiList.add(userAnswerBo);
                    }
                    if (userAnswerBo.getType() == 2) {
                        judgeList.add(userAnswerBo);
                    }
                }
            }
        }
        List<UserAnswerBo> randomArrayElements = getRandomArrayElements(singleList);
        List<UserAnswerBo> randomArrayElements1 = getRandomArrayElements(multiList);
        List<UserAnswerBo> randomArrayElements2 = getRandomArrayElements(judgeList);
        randomArrayElements.addAll(randomArrayElements1);
        randomArrayElements.addAll(randomArrayElements2);

        paper.setTheoryQuestion(AESEncrypt.encode(paper.getKey(), paper.getTheoryQuestion(), paper.getIv().getBytes()));
        return ResultT.success(paper);

    }

    //随机返回数据
    public List<UserAnswerBo> getRandomArrayElements(List<UserAnswerBo> list) {
        List<UserAnswerBo> bos = new ArrayList<>();
        if (CollUtil.isNotEmpty(list)) {
            for (int i = list.size(); i >= 0; i--) {
                int num = (int) (Math.random() * i);
                bos.add(list.get(num));
            }
        }
        return bos;
    }


    @PostMapping("/task/scheduledAnswer")
    @ApiOperation("及时提交")
    public ResultT scheduledAnswer(@RequestBody ScheduledAnswerVo scheduledAnswerVo) {
        String courseId = scheduledAnswerVo.getCourseId();
        String taskId = scheduledAnswerVo.getTaskId();
        String paperId = scheduledAnswerVo.getPaperId();
        int userId = StpUtil.getLoginIdAsInt();

        String uniqueStr = courseId + "-" + taskId + "-" + paperId + "-" + userId;
        AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, "w2SIy2Hx%2i!tTCd-ikwHEv_kQmB58xI".getBytes(), "R7#54X&gLB!6Q&s=".getBytes());
        String decryptStr = aes.decryptStr(scheduledAnswerVo.getUserAnswer(), CharsetUtil.CHARSET_UTF_8);
        ScheduledAnswerBo scheduledAnswerBo = new ScheduledAnswerBo();
        scheduledAnswerBo.setTimeUse(scheduledAnswerVo.getTimeUse().toString());
        scheduledAnswerBo.setUserAnswer(decryptStr);
        redisTemplate.opsForValue().set(uniqueStr, JSON.toJSONString(scheduledAnswerBo));
        Paper paper = paperService.getById(paperId);

        if (scheduledAnswerVo.getTimeUse().intValue() <= paper.getExamTime()) {

            return ResultT.success("操作成功");
        } else {
            Object object = redisTemplate.opsForValue().get(uniqueStr);

            scheduledAnswerVo.setUserAnswer(object.toString());
            ResultT resultT = courseService.commitPaper(scheduledAnswerVo);

            return resultT;
        }
    }


    @PostMapping("/commitPaper")
    @ApiOperation("交卷")
    public ResultT commitPaper(@RequestBody ScheduledAnswerVo scheduledAnswerVo) {
        ResultT resultT = courseService.commitPaper(scheduledAnswerVo);
        return resultT;
    }

    @PostMapping("/task/commitPaper")
    @ApiOperation("交卷")
    public ResultT tasKcommitPaper(@RequestBody ScheduledAnswerVo scheduledAnswerVo) {
        ResultT resultT = courseService.tasKcommitPaper(scheduledAnswerVo);
        return resultT;
    }

    @PostMapping("/task/updateStatus")
    @ApiOperation("判断是否完成交卷")
    public ResultT taskupdateStatus(@RequestBody TaskUpdateStatus taskUpdateStatus) {
        String courseId = taskUpdateStatus.getCourseId();
        String taskId = taskUpdateStatus.getTaskId();
        Integer status = taskUpdateStatus.getStatus();

        Boolean update = false;
        LambdaQueryWrapper<Taskprogress> lqw = new LambdaQueryWrapper<>();
        lqw.eq(courseId != null, Taskprogress::getCourseId, courseId).eq(Taskprogress::getUserId, StpUtil.getLoginIdAsInt());
        lqw.eq(taskId != null, Taskprogress::getTaskId, taskId).orderByAsc().orderByDesc(Taskprogress::getCreateTime).last(" limit 1");
        Taskprogress taskprogress = taskprogressService.getOne(lqw);
        if (BeanUtil.isEmpty(taskprogress)) {
            taskprogress = new Taskprogress();
            taskprogress.setUserId(StpUtil.getLoginIdAsInt());
            taskprogress.setCourseId(Integer.valueOf(taskUpdateStatus.getCourseId()));
            taskprogress.setTaskId(Integer.valueOf(taskUpdateStatus.getTaskId()));
            taskprogress.setCreateTime(DateUtil.formatDateTime(new Date()));
            taskprogress.setIsFinished(status == 0 ? false : true);
            update = taskprogressService.save(taskprogress);
        } else {
            taskprogress.setIsFinished(status == 0 ? false : true);
            update = taskprogressService.updateById(taskprogress);
        }
        if (update) {
            return ResultT.success("操作成功");
        } else {
            return ResultT.fail("操作失败");
        }
    }


    @PostMapping("/updateStatus")
    @ApiOperation("判断是否完成交卷")
    public ResultT updateStatus(@RequestBody TaskUpdateStatus taskUpdateStatus) {
        String courseId = taskUpdateStatus.getCourseId();
        String taskId = taskUpdateStatus.getTaskId();
        Integer status = taskUpdateStatus.getStatus();


        LambdaQueryWrapper<Taskprogress> lqw = new LambdaQueryWrapper<>();
        lqw.eq(courseId != null, Taskprogress::getCourseId, courseId);
        lqw.eq(taskId != null, Taskprogress::getTaskId, taskId);

        Taskprogress taskprogress = taskprogressService.getOne(lqw);
        taskprogress.setIsFinished(status == 0 ? false : true);

        boolean update = taskprogressService.updateById(taskprogress);

        if (update) {
            return ResultT.success("操作成功");
        } else {
            return ResultT.fail("操作失败");
        }
    }
}
